var express = require('express');
var router = express.Router();
var utils = require('../functions/utils');

// share 기능 , share count 체크
router.post('/', function(req,res)
{
/*
	Input parameters 

	 *		encArticleId			enc아티클ID
*/
	var encArticleId = req.body.encArticleId;			utils.checkParamValue( 'encArticleId' , encArticleId);

	var dbData = null;
	var state = null;
	var articleId = null;
	var keyword = '';

	// 읽는건 replica 
	global.replica_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var profileImageSizeId = 2; // 프로파일 이미지 작은거
		var thumbnailSizeId = 2; // 섬네일 이미지 작은거 

		var input_param = [encArticleId 
				, global.config.web.appId , global.config.web.appVersion 
				, profileImageSizeId , thumbnailSizeId ,global.config.storage.download.url , global.config.storage.download.secretUrl];

		var sql = 'call api_getSingleArticleViewPageInfoWithKeyword(? , ? , ? , ? , ? , ? , ?, @articleId , @state , @webKeyword , @tagList ); ';
		sql += 'SELECT @articleId as articleId ,  @state as state , @webKeyword as webKeyword , @tagList as tagList ';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }

			// 아티클 결과가 없을 경우 : 에러 , 없는아티클id , 삭제아티클
			if(rows.length <= 2)
			{
				state = rows[1][0].state;

				// 에러가 났을 경우 :code : 523		
				if(state == null)
				{
					var err = new Error('No article for encId: ' + encArticleId);
					err.code = '523';
					throw err;
				}
			}
			// 결과있음.
			else
			{

				state = rows[2][0].state;
				articleId = rows[2][0].articleId;

				if(utils.isValidString(rows[2][0].webKeyword))
				{
					keyword = rows[2][0].webKeyword;
				}
				if(utils.isValidString(rows[2][0].tagList))
				{
					if(utils.isValidString(keyword))
						keyword += ',' + rows[2][0].tagList;
					else
						keyword = rows[2][0].tagList;
				}

				dbData = rows[0][0];
				dbData.keyword = keyword;

				// view count 올린다
				utils.incPageViewCount(articleId , global.config.web.appId , global.config.web.appVersion );

			}


			var ret = {code : 200 };	 // 에러아니면 일단 성공

			// 아티클 내용이 올 경우
			if(dbData != null) 
			{
				ret.body = dbData;
				ret.body.state = state;
			}
			// 없을 경우
			else
			{
				ret.body = {state : state};
			}

			res.json(ret);
			res.end();


		}); // call api_incShareCount

	}); // getConnection



});



router.get('/:encryptedId', function(req,res)
{
/*
	// maintenance
	var maintenance_content='<html><body><h2><br><br><center> We are so sorry.<br>We are under maintenance for 1 hour.</center></body></html>';
	res.end(maintenance_content);
	return;
*/

	utils.callLog(req);

	var encArticleId = req.params.encryptedId;

	var async = require('async');
	var dbData = null;
	var state = null;
	var articleId = null;
	var keyword = '';

	async.series(
		[
			// db 
			function(CB)
			{
				// 읽는건 replica 
				global.replica_db.connection.getConnection(function(err,connection)
				{
					if(err) { throw err; }

					var profileImageSizeId = 2; // 프로파일 이미지 작은거
					var thumbnailSizeId = 2; // 섬네일 이미지 작은거 

					var input_param = [encArticleId 
							, global.config.web.appId , global.config.web.appVersion 
							, profileImageSizeId , thumbnailSizeId ,global.config.storage.download.url , global.config.storage.download.secretUrl];

					var sql = 'call api_getSingleArticleViewPageInfoWithKeyword(? , ? , ? , ? , ? , ? , ?, @articleId , @state , @webKeyword , @tagList ); ';
					sql += 'SELECT @articleId as articleId ,  @state as state , @webKeyword as webKeyword , @tagList as tagList ';

					var query = connection.query(sql, input_param , function (err, rows) 
					{
						connection.release();
						if(err) { throw err; }


						// 에러나 결과가 없을 경우도 화면에는 표시해줘야하므로 - 에러날리지 않음. 
						// 결과가 없을 경우 
						if(rows.length  > 2 && rows[0].length == 0)
						{
							state = 20;	// 리턴된 데이터 없으면 삭제된거.
						}
						// 에러났을 경우 
						else if(rows.length == 2)
						{
							state = rows[1][0].state;
						}
						// 결과있음.
						else
						{
							articleId = rows[2][0].articleId;

							if(utils.isValidString(rows[2][0].webKeyword))
							{
								keyword = rows[2][0].webKeyword;
							}
							if(utils.isValidString(rows[2][0].tagList))
							{
								if(utils.isValidString(keyword))
									keyword += ',' + rows[2][0].tagList;
								else
									keyword = rows[2][0].tagList;
							}


							if(utils.isValidString(keyword))
							{
								keyword = keyword.split('"').join('\'');
							}

							dbData = rows[0][0];
						}

						// next step
						CB(null);

					}); // call api_incShareCount

				}); // getConnection
	
			}
			// read tempate 
			,function(CB)
			{
				// 기존에 없을 경우만 읽는다
				if(global.singleArticleView_template == null)
				{
					var fs = require('fs');
					fs.readFile('./template/page/singleArticleView' , function(error,data)
					{
						if(error)
						{
							utils.error("loadVideoPage : template read error");
							throw err;
						}
						global.singleArticleView_template = String(data);
						utils.debug('loadVideoPage : read template page');

						// next step
						CB(null);
					});
				}
				else
				{
						// next step
						CB(null);
				}

			}
		]
		,function(err, results) 
		{
			var content = global.singleArticleView_template;

			// 결과있음.
			if(dbData)
			{

				// 없으면 (그럴 일은 없지만) ALIVE
				if(!utils.isValidString(dbData.userName))
				{
					dbData.userName = 'ALIVE';
				}
				content = content.split("%NICK_VALUE%").join(utils.adjustPropValue(dbData.userName));
				content = content.split("%NICK_STRING%").join(utils.adjustHTMLString(dbData.userName));

//dbData.articleBody = 'Biotine, or vitamin H, also called B8, is a hydrosoluble (water soluble) vitamin which the body can store either very little or not at all. This vitamin is essential for the growth of skin appendages (in the case of the horse, hoof walls, hair and mane). But it is not sufácient to take this vitamin on its own; it also needs trace elements of sulphur to be optimally absorbed by the body. This is because all skin appendages are largely composed of sulphur. So you cannot have one without the other. BIOTINE + is formulated with nettle and horsetail, known and renowned for their goodness and in particular for providing bioavailable silicon, very easily absorbed by the horse. This silicon strengthens the structure of the hoof walls and the hoof itself. HUSSE has specially formulated BIOTINE + to meet every need of the skin appendages and remedy any possible deáciencies of either vitamins or trace elements. It is this synergy of beneáts that enables quality hoof walls and hair.';



				// 넣지 않는 경우도 많음 - 없으면 value만 user name 넣는다. (twitter에는 내용없으면 미디어 노출되지 않음)
				if(utils.isValidString(dbData.articleBody))
				{
					content = content.split("%ARTICLE_BODY_VALUE%").join(utils.adjustPropValue(dbData.articleBody));
					content = content.split("%ARTICLE_BODY_STRING%").join(utils.adjustHTMLString(dbData.articleBody));
					content = content.split("%TITLE_VALUE%").join(utils.adjustPropValue(dbData.articleBody));

					content = content.split("%SHOW_DESCRIPTION%").join('');
				}
				else
				{
					//content = content.split("%ARTICLE_BODY_VALUE%").join(utils.adjustPropValue('ALIVE | Creative Expressionism'));
					content = content.split("%ARTICLE_BODY_VALUE%").join(utils.adjustHTMLString(''));
					content = content.split("%ARTICLE_BODY_STRING%").join(utils.adjustHTMLString(''));
					content = content.split("%TITLE_VALUE%").join('');

					content = content.split("%SHOW_DESCRIPTION%").join('hidden');
				}


				content = content.split("%WEB_KEYWORD%").join(keyword);

				content = content.split("%PROFILE_IMAGE_URL%").join(utils.isValidString(dbData.profilePicPath) 
											? dbData.profilePicPath : global.config.web.defaultProfileImageUrl);

				var str = '';
				if(dbData.diffDate == 0)
					str = 'today';
				else if(dbData.diffDate < 7)
					str = dbData.diffDate + ' D ago';
				else
					str = parseInt(dbData.diffDate/7) + ' W ago';

				content = content.split("%DAY_DIFFERENCE%").join(str);

				if(dbData.viewCount > 1000)
				{
					str = (dbData.viewCount/1000).toFixed(1)+'k';
					content = content.split("%VIEW_COUNT%").join(str);
				}
				else
					content = content.split("%VIEW_COUNT%").join(dbData.viewCount);
				
				content = content.split("%LIKE_COUNT%").join(utils.commaNum(dbData.likeCount));
				if(dbData.likeCount == 0)
					content = content.split("%SHOW_LIKE%").join('hidden');
				else
					content = content.split("%SHOW_LIKE%").join('');


				content = content.split("%THUMB_URL%").join(utils.isValidString(dbData.thumbUrl) ? dbData.thumbUrl : '');
				content = content.split("%VIDEO_URL%").join(utils.isValidString(dbData.videoUrl) ? dbData.videoUrl : '');
				content = content.split("%VIDEO_SECRET_URL%").join(utils.isValidString(dbData.videoSecretUrl) ? dbData.videoSecretUrl : '');
				content = content.split("%HLS_URL%").join(utils.isValidString(dbData.hlsUrl) ? dbData.hlsUrl : '');

				content = content.split("%REG_DATE%").join(dbData.regDate);

				content = content.split("%VIDEO_WIDTH%").join(dbData.width);
				content = content.split("%VIDEO_HEIGHT%").join(dbData.height);

				// view count 올린다
				utils.incPageViewCount(articleId , global.config.web.appId , global.config.web.appVersion );

			}
			// 게시물 없음.
			else
			{

				content = content.split("%NICK_VALUE%").join('');
				content = content.split("%NICK_STRING%").join('');

				content = content.split("%ARTICLE_BODY_VALUE%").join('');
				content = content.split("%ARTICLE_BODY_STRING%").join('');
				content = content.split("%TITLE_VALUE%").join('');

				content = content.split("%SHOW_DESCRIPTION%").join('hidden');


				content = content.split("%WEB_KEYWORD%").join(keyword);

				content = content.split("%PROFILE_IMAGE_URL%").join(global.config.web.defaultProfileImageUrl);

				content = content.split("%DAY_DIFFERENCE%").join('');

				content = content.split("%VIEW_COUNT%").join('');
				
				content = content.split("%LIKE_COUNT%").join('');
				content = content.split("%SHOW_LIKE%").join('hidden');

				content = content.split("%THUMB_URL%").join(global.config.web.deletedArtlcleImageUrl);
				content = content.split("%VIDEO_URL%").join('');
				content = content.split("%VIDEO_SECRET_URL%").join('');
				content = content.split("%HLS_URL%").join('');

				content = content.split("%REG_DATE%").join('');

				content = content.split("%VIDEO_WIDTH%").join('');
				content = content.split("%VIDEO_HEIGHT%").join('');


			}

			// 공통부분 - 설정에 있는 url 적어주는 부분들 
			content = content.split("%ENC_ID%").join(encArticleId); 

			content = content.split("%VIEW_PAGE_URL%").join(global.config.web.viewPageUrl + encArticleId);
			content = content.split("%SECURE_VIEW_PAGE_URL%").join(global.config.web.secureViewPageUrl + encArticleId);
			content = content.split("%EMBEDDED_PAGE_URL%").join(global.config.web.embeddedPageUrl + encArticleId); //twitter : https
			
			content = content.split("%LIKED_ARTICLELIST_URL%").join(global.config.web.likedArticleListUrl+articleId);
			content = content.split("%INC_SHARE_PAGE_URL%").join(global.config.web.incPageShareCountUrl);

			content = content.split("%APPLE_STORE_URL%").join(global.config.web.appleStoreUrl);
			content = content.split("%GOOGLE_STORE_URL%").join(global.config.web.googleStoreUrl);

			content = content.split("%PRIVACY_URL%").join(global.config.web.privacyUrl);
			content = content.split("%TERMS_URL%").join(global.config.web.termsUrl);
			content = content.split("%FAQ_URL%").join(global.config.web.faqUrl);


	
			res.writeHead(200 , {'Content-Type' : 'text/html'});
			res.end(content);

		}
	);
	
});

module.exports = router;